package com.itheima.wms.config;

import com.itheima.pinda.base.R;
import com.itheima.pinda.common.handler.DefaultGlobalExceptionHandler;
import com.itheima.pinda.exception.code.ExceptionCode;
import com.itheima.pinda.utils.StrPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@Configuration
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class ExceptionConfiguration extends DefaultGlobalExceptionHandler {

    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> duplicateKeyException(DuplicateKeyException ex, HttpServletRequest request) {
        log.warn("DuplicateKeyException", ex);

//### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'CK002' for key 'wms_warehouse.warehouse_code'
//### The error may exist in com/itheima/wms/dao/WarehouseMapper.java (best guess)
//### The error may involve com.itheima.wms.dao.WarehouseMapper.insert-Inline
//### The error occurred while setting parameters
//### SQL: INSERT INTO wms_warehouse  ( id, code, name, type, province, city, area, address, surface,  person_name, phone, included_num, status, remark,    update_time, update_user, create_time, create_user )  VALUES  ( ?, ?, ?, ?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?,    ?, ?, ?, ? )
//### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'CK002' for key 'wms_warehouse.warehouse_code'
//        ; Duplicate entry 'CK002' for key 'wms_warehouse.warehouse_code'; nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'CK002' for key 'wms_warehouse.warehouse_code'

        try {
            String[] exMessage = ex.getMessage().split("###");
            String message = exMessage[1].split("Duplicate entry '")[1].split("' for key")[0];
            R<String> r = R.result(ExceptionCode.ILLEGALA_ARGUMENT_EX.getCode(), StrPool.EMPTY, message + " 已存在!");
            r.setPath(request.getRequestURI());
            return r;
        } catch (Exception e) {
            R<String> r = R.result(ExceptionCode.SQL_EX.getCode(), StrPool.EMPTY, ExceptionCode.SQL_EX.getMsg());
            r.setPath(request.getRequestURI());
            return r;
        }
    }
}
